package callnumber.gtdev5.com.photoVault.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.gtdev5.geetolsdk.mylibrary.util.ToastUtils;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import callnumber.gtdev5.com.photoVault.R;
import callnumber.gtdev5.com.photoVault.bean.FileNameBean;
import callnumber.gtdev5.com.photoVault.utils.ImageBase64;
import callnumber.gtdev5.com.photoVault.utils.ImageUtils;

/**
 * 图片查看器
 */
public class ImagePagerActivity extends FragmentActivity {
    private static final String STATE_POSITION = "STATE_POSITION";
    public static final String EXTRA_IMAGE_INDEX = "image_index";
    TextView text_export;
    private HackyViewPager mPager;
    private int pagerPosition;
    private int ids;
    private TextView indicator;
    List<Bitmap> urls = new ArrayList<>();
    private List<FileNameBean> dataName;
    int i;
    ImageView iv_back;
    //    private List<FileNameBean> dataName;
    ImagePagerAdapter mAdapter;
    //    ArrayList<String> infoList;
    List<String> stringList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_detail_pager);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.black));
        }
        ids = getIntent().getIntExtra("ids", ids);
        pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
        text_export = findViewById(R.id.text_export);
        iv_back = findViewById(R.id.iv_back);
        dataName = new ArrayList<>();
        dataName = DataSupport.where("ids = ?", ids + "").find(FileNameBean.class);
        if (dataName != null && !dataName.isEmpty()) {
            for (FileNameBean fileNameBean : dataName) {
                if (ImageUtils.fileIsExists(fileNameBean.getName())) {
                    String text = fileNameBean.getName();
                    ImageUtils.renameFile(fileNameBean.getName(), text);
//                    File file = new File(text);
//                    String s = ImageUtils.getFileContent(file);
//                    String con = Des3Util.decrypt(key, s);
                    Bitmap bitmap = BitmapFactory.decodeFile(text);//从路径加载出图片bitmap
                    urls.add(bitmap);
                }

            }

        }


        i = pagerPosition;
        mPager = (HackyViewPager) findViewById(R.id.pager);
        mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), (ArrayList<Bitmap>) urls);
        mPager.setAdapter(mAdapter);
        indicator = (TextView) findViewById(R.id.indicator);

        CharSequence text = getString(R.string.viewpager_indicator, 1, mPager.getAdapter().getCount());
        indicator.setText(text);

        // 更新下标

        mPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int arg0) {
                CharSequence text = getString(R.string.viewpager_indicator, arg0 + 1, mPager.getAdapter().getCount());
                i = arg0;
                indicator.setText(text);
            }

        });
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间

        Date date = new Date(System.currentTimeMillis());
        text_export.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stringList = new ArrayList<>();
                stringList.add(i + "");
                saveBitmap(urls.get(i), simpleDateFormat.format(date) + ".JPEG");
                urls.remove(i);

                mAdapter.notifyDataSetChanged();
                DataSupport.deleteAll(FileNameBean.class, "name = ?", dataName.get(i).getName());
                if (urls.size() == 0) {
                    finish();
                }
//                DataSupport.delete(FileNameBean.class, dataName.get(i).getId());

            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (stringList == null || stringList.size()==0) {
                    finish();
                } else{
                    Intent intent = new Intent();
                    intent.putStringArrayListExtra("mes", (ArrayList<String>) stringList);//返回值
                    setResult(115, intent);
                    finish();
                }
            }
        });
        if (savedInstanceState != null) {
            pagerPosition = savedInstanceState.getInt(STATE_POSITION);
        }

        mPager.setCurrentItem(pagerPosition);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_POSITION, mPager.getCurrentItem());

    }

    private class ImagePagerAdapter extends FragmentStatePagerAdapter {

        public ArrayList<Bitmap> fileList;
        public ImagePagerAdapter(FragmentManager fm, ArrayList<Bitmap> fileList) {
            super(fm);
            this.fileList = fileList;
        }

        @Override
        public int getCount() {
            return fileList == null ? 0 : fileList.size();
        }

        @Override
        public Fragment getItem(int position) {
            Bitmap url = fileList.get(position);
            return ImageDetailFragment.newInstance(url);
        }

        @Override
        public int getItemPosition(Object object) {
            // 最简单解决 notifyDataSetChanged() 页面不刷新问题的方法
            return POSITION_NONE;
        }

    }

    public void saveBitmap(Bitmap bitmap, String bitName) {
        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
// 插入图库
                MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), bitName, null);

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
        // 发送广播，通知刷新图库的显示
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        ToastUtils.showShortToast("导出成功");

    }
}
